import React from 'react';
import './index.scss';
import emitter from '../emitter';
import {getGuid} from "../../../src/utils";

export default class extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            timeline: 500,
            actors: [],
            showContextMenu: false,
            showImportContext: false,
            menuX: 0,
            menuY: 0,
            currentFrame: 0,
            nodeId: 0,
        };
    }

    componentDidMount() {
        emitter.on('new:node:created', (args) => {
            const { id, style } = args;
            const { actors = [] } = this.state;
            const scheduleId = getGuid();
            actors.push({
                id,
                isSelect: true,
                name: '未命名',
                schedulers: [{
                    id: scheduleId,
                    delay: 0,
                    style,
                }], // 关键帧
                selectScheduler: scheduleId,
                tweens: [], // 补间动画
            });
            this.setState({
                actors,
            });
        });
        emitter.on('select:node', (args) => {
            const { id, style } = args;
            const { actors = [] } = this.state;
            let actorIndex = actors.findIndex(vo => vo.isSelect === true);
            if (actorIndex >= 0) {
                actors[actorIndex].isSelect = false;
            }
            actorIndex = actors.findIndex(vo => vo.id === id);
            if (actorIndex >= 0) {
                actors[actorIndex].isSelect = true;
            }
            this.setState({
                actors,
            });
        });
        emitter.on('node:keyframe:style', (args) => {
           const { id, style } = args;
           const { actors = [] } = this.state;
           const actorIndex = actors.findIndex(vo => vo.id === id);
           console.log('style====>', actorIndex, style, id);
           if (actorIndex >= 0) {

               const actor = actors[actorIndex];
               const { selectScheduler, schedulers = [] } = actor;
               const schedulerIndex = schedulers.findIndex(vo => vo.id === selectScheduler);
               if (schedulerIndex >= 0) {
                   const scheduler = schedulers[schedulerIndex];
                   const currentStyle = scheduler.style;
                   Object.assign(currentStyle, style);
                   this.setState({
                       actors,
                   });
               }
           }
        });
    }

    onShowMenu = (e, index, id) => {
        e.preventDefault();
        this.setState({
            showContextMenu: true,
            menuX: e.pageX,
            menuY: e.pageY,
            currentFrame: index,
            nodeId: id,
        });
    }

    onAddImport = () => {
        const { currentFrame, nodeId, actors } = this.state;
        const actorIndex = actors.findIndex(vo => vo.id === nodeId);
        if (actorIndex >= 0) {
            const schedulerId = getGuid();
            actors[actorIndex].schedulers.push({
                id: schedulerId,
                delay: currentFrame * 100,
                style: {},
            });
            actors[actorIndex].selectScheduler = schedulerId;
            console.log('actor===>', actors);
            this.setState({
                actors,
                showContextMenu: false,
            });
        }
    }
    // 创建补间动画
    onAddTween = () => {
        const  { currentFrame, nodeId, actors } = this.state;
        const actorIndex = actors.findIndex(vo => vo.id === nodeId);
        if (actorIndex >= 0) {
            const { schedulers = [], tweens = [] } = actors[actorIndex];
            let startFrame = -1;
            let startLen = Number.MAX_VALUE;
            let endFrame = -1;
            let endLen = Number.MAX_VALUE;
            for (let i = 0; i < schedulers.length; i++) {
                const scheduler = schedulers[i];
                const diff = scheduler.delay - currentFrame * 100;
                if (diff < 0 && Math.abs(diff) < startLen) {
                    startLen = Math.abs(diff);
                    startFrame = i;
                }
                if (diff > 0 && diff < endLen) {
                    endFrame = i;
                    endLen = diff;
                }
            }
            if (startFrame >= 0 && endFrame >= 0) {
                tweens.push({
                    start: schedulers[startFrame].id,
                    end: schedulers[endFrame].id,
                });
                actors[actorIndex].tweens = tweens;
                this.setState({
                    actors,
                    showContextMenu: false,
                });
            } else {
                this.setState({
                    showContextMenu: false,
                })
                alert('没有对应的关键帧');
            }
        }
    }

    onActorClick = (id) => {
        const { actors, nodeId } = this.state;
        if (nodeId === id) {
            return;
        }
        const actorIndex = actors.findIndex(vo => vo.id === id);
        if (actorIndex >= 0) {
            const actor = actors[actorIndex];

        }
    }

    onImportClick = (id, scheduleId) => {
        const { actors = [] } = this.state;
        const actorIndex = actors.findIndex(vo => vo.id === id);
        if (actorIndex >= 0) {
            const schedulerIndex = actors[actorIndex].schedulers.findIndex(vo => vo.id === scheduleId);
            if (schedulerIndex >= 0) {
                const scheduler = actors[actorIndex].schedulers[schedulerIndex];
                actors[actorIndex].selectScheduler = scheduler.id;
                this.setState({
                    actors,
                }, () => {
                    emitter.emit('node:keyframe:select', { id, style: scheduler.style });
                });
            }
        }
    }

    onImportMenu = (e, actorId, schedulerId) => {
        e.preventDefault();
        const { actors = [] } = this.state;
        const actorIndex = actors.findIndex(vo => vo.id === actorId);
        if (actorIndex >= 0) {
            const schedulerIndex = actors[actorIndex].schedulers.findIndex(vo => vo.id === schedulerId);
            if (schedulerIndex >= 0) {
                const scheduler = actors[actorIndex].schedulers[schedulerIndex];
                actors[actorIndex].selectScheduler = scheduler.id;
                this.setState({
                    menuX: e.pageX,
                    menuY: e.pageY,
                    actors,
                    nodeId: actorId,
                    showImportContext: true,
                }, () => {
                    emitter.emit('node:keyframe:select', { id: actorId, style: scheduler.style });
                });
            }
        }
    }

    onRemoveImport = () => {
        const { actors = [], nodeId } = this.state;
        const actorIndex = actors.findIndex(vo => vo.id === nodeId);
        if (actorIndex >= 0) {
            if (actors[actorIndex].schedulers.length > 1) {
                const actor = actors[actorIndex];
                const schedulerId = actor.selectScheduler;
                const schedulerIndex = actor.schedulers.findIndex(vo => vo.id === schedulerId);
                const tweenIndex = actor.tweens.findIndex(vo => vo.start === schedulerId || vo.end === schedulerId);
                if (tweenIndex >= 0) {
                    actor.tweens.splice(tweenIndex, 1);
                }
                actor.schedulers.splice(schedulerIndex, 1);
                const scheduler = actors[actorIndex].schedulers[0];
                actor.selectScheduler = scheduler.id;
                this.setState({
                    actors,
                    showImportContext: false,
                }, () => {
                    emitter.emit('node:keyframe:select', { id: nodeId, style: scheduler.style });
                });
            } else {
                this.setState({
                    showImportContext: false,
                }, () => {
                    alert('当前元素无其他关键帧');
                });
            }
        }
    }

    render() {
        const { timeline, actors, showContextMenu, menuX, menuY, showImportContext = false } = this.state;
        const timesplit = [];
        for (let i = 0 ; i <= timeline; i++) {
            timesplit.push(i);
        }
        return (
            <React.Fragment>
                <div className="progress-box">
                    <div className="progress-editor">
                        <div className="progress-editor-bar">

                        </div>
                        {
                            actors.map(vo => {
                                return (
                                    <div
                                        className={`progress-editor-content-item ${vo.isSelect ? 'active' : ''}`}
                                        data-id={vo.id}
                                        onClick={() => this.onActorClick(vo.id)}
                                    >
                                        { vo.name }
                                    </div>
                                )
                            })
                        }
                    </div>
                    <div className="progress-time-line">
                        <div className="progress-time-bar">
                            {
                                timesplit.map(vo => {
                                    if (vo % 10 === 0) {
                                        return (
                                            <div className="progress-time-item">
                                                <div className="progress-time-item-text">{vo === 0 ? vo / 10 : `${vo / 10}s`}</div>
                                                <div className="progress-time-item-line long" />
                                            </div>
                                        );
                                    } else {
                                        return (
                                            <div className="progress-time-item">
                                                <div className="progress-time-item-text">&nbsp;&nbsp;</div>
                                                <div className="progress-time-item-line short" />
                                            </div>
                                        )
                                    }
                                })
                            }
                        </div>
                        {
                            actors.map(vo => {
                                return (
                                    <div className={`progress-time-bar ${vo.isSelect ? 'active' : ''}`}>
                                        {
                                            timesplit.map(item => {
                                                const actionIndex = vo.schedulers.findIndex(v => v.delay === item * 100);
                                                // 关键帧
                                                if (actionIndex >= 0) {
                                                    return (
                                                        <div
                                                            className="progress-time-item-box action"
                                                            onClick={(e) => this.onImportClick(vo.id, vo.schedulers[actionIndex].id)}
                                                            onContextMenu={(e) => this.onImportMenu(e, vo.id, vo.schedulers[actionIndex].id)}
                                                        >
                                                            <div className={`progress-time-import start ${vo.schedulers[actionIndex].id === vo.selectScheduler ? 'active' : ''}`}/>
                                                        </div>
                                                    )
                                                }
                                                // const targetActionIndex = vo.schedulers.findIndex(v => v.delay + v.action.duration === item * 100);
                                                // if (targetActionIndex >= 0) {
                                                //     return (
                                                //         <div className="progress-time-item-box action">
                                                //             <div className="progress-time-import target"/>
                                                //         </div>
                                                //     );
                                                // }
                                                let inAction = false;
                                                for (let i = 0; i < vo.tweens.length; i++) {
                                                    const tween = vo.tweens[i];
                                                    const startScheduler = vo.schedulers.findIndex(m => m.id === tween.start);
                                                    const endScheduler = vo.schedulers.findIndex(m => m.id === tween.end);
                                                    if (startScheduler >= 0 && endScheduler >= 0) {
                                                        if (item * 100 > vo.schedulers[startScheduler].delay && item * 100 < vo.schedulers[endScheduler].delay) {
                                                            inAction = true;
                                                        }
                                                    }

                                                }
                                                if (inAction) {
                                                    return <div className="progress-time-item-box action" />
                                                }

                                                return (
                                                    <div
                                                        className="progress-time-item-box"
                                                        onContextMenu={(e) => this.onShowMenu(e, item, vo.id)}
                                                    ></div>
                                                );
                                            })
                                        }
                                    </div>
                                )
                            })
                        }
                    </div>
                </div>
                {
                    showContextMenu && (
                        <div
                            className="context-menu-box"
                            style={{
                                left: `${menuX}px`,
                                top: `${menuY}px`
                            }}
                        >
                            <div className="context-menu-item" onClick={this.onAddImport}>插入关键帧</div>
                            <div className="context-menu-item" onClick={this.onAddTween}>创建补间动画</div>
                        </div>
                    )
                }
                {
                    showImportContext && (
                        <div
                            className="context-menu-box"
                            style={{
                                left: `${menuX}px`,
                                top: `${menuY}px`
                            }}
                        >
                            <div className="context-menu-item" onClick={this.onRemoveImport}>删除关键帧</div>
                        </div>
                    )
                }
            </React.Fragment>
        );
    }
}
